// pages/video/video.js
const app = getApp()

function getRandomColor() {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
Page({

  /**
   * Page initial data
   */

  data: {
    videoContent: '',
    inputValue: '',
    sentence: '',
    dkheight: 50,
    originUrl: '',
    name: '',
    danmuList: [{
        text: 'Guten Tag!',
        color: '#ff0000',
        time: 1
      },
      {
        text: '没有人吗？',
        color: '#ff00ff',
        time: 12
      }
    ]
  },

  bindInputBlur: function(e) {
    this.inputValue = e.detail.value
  },
  bindSendDanmu() {
    this.inputValue = ''
    this.videoContext.sendDanmu({
      text: this.inputValue,
      color: getRandomColor()
    })
  },
  bilibili(av) {
    let _this = this
    wx.request({
      header: app.globalData.header,
      url: `https://api.bilibili.com/playurl?callback=callbackfunction&aid=${av}&page=1&platform=html5&quality=1&vtype=mp4&type=jsonp`,
      header: {
        Cookie: `CURRENT_FNVAL=16; buvid3=A5866C41-3EB6-431C-92A7-BDED443B21CA110263infoc; sid=adalxz04; stardustvideo=1; LIVE_BUVID=AUTO7615553074499458; fts=1555474025; UM_distinctid=16a43719d16560-0c6616bd7adf7e-36697e04-384000-16a43719d178cf; rpdid=|(JY)RJ))|~m0J'ullY|ulRlm; CURRENT_QUALITY=80; im_notify_type_267859889=0; DedeUserID=267859889; DedeUserID__ckMd5=06773895ee640544; SESSDATA=9f37594d%2C1560787192%2C19e7cb51; bili_jct=362f53407c37211fa1e8618736c72284; finger=1e7fd4f8; _dfcaptcha=5de5d45155081dcdbc0a6369295d5d61; bp_t_offset_267859889=261534946796702184`
      },
      success(res) {
        let entity = JSON.parse(res.data.replace('callbackfunction(', '').replace(');', ''))
        let videoSrc = entity.durl[0].url.replace("http", "https")
        let videoContent = {}
        videoContent.videoSrc = videoSrc
        _this.setData({
          videoContent: videoContent
        })
      }
    })
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    console.error("global", app.globalData.header.Cookie)

    wx.showLoading({
      title: '努力加载中...',
    })
    let serverUrl = app.serverUrl
    let _this = this
    console.log("params", options)
    if (options.title != undefined) {
      _this.setData({
        title: options.title
      })
    }
     if (options.title == undefined &&options.name!=undefined) {
      _this.setData({
        title: options.name
      })
    }
    if (options.av != undefined) {
      _this.bilibili(options.av)
      if (options.desc != undefined) {
        let desc = decodeURI(options.desc)
        _this.setData({
          sentence: desc
        })
      }

    } else {
      _this.setData({
        name: options.name,
        originUrl: options.url
      })
      if (options.share != undefined) {
        _this.setData({
          share: options.share
        })
      }
      let _url = decodeURIComponent(options.url)
      console.log("_u", _url)
      let url = `${serverUrl}/dic/video?url=${_url}&title=${_this.data.title}&share=${_this.data.share}`
      // let url = `http://localhost:888/dic/video?url=${_url}`
      wx.request({
        header: app.globalData.header,
        url: url,
        method: "GET",
        success: function(res) {
          let N = []
          if (res.data.code == 0) {
            wx.hideLoading()
            if (res.data.content.videoSrc == "") {
              wx.showToast({
                title: '页面不存在了!',
                icon: 'none'
              })
              setTimeout(wx.navigateBack, 800)
            }
            console.log("res", res.data.content.content)
            let _sentence = res.data.content.content.split(". ")
            _sentence.forEach(item => {
              if (item)
                N.push(item)
            })
            _this.setData({
              videoContent: res.data.content,
              sentence: N
            })
            // wxparse.wxParse('dkcontent', 'html', res.data.content, this, 5);

          } else {
     
          }

        }
      })

    }


  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function(res) {
    this.videoContext = wx.createVideoContext('myVideo')
  },
  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {

  },
  wxLogin() {

    let _this = this
    wx.login({
      success(res) {
        _this.setData({
          id: res.code
        })
        console.error('res.code', res.code)
        wx.getSetting({
          success: function(ret) {

            wx.getUserInfo({
              lang: "zh_CN",
              withCredentials: true,
              success: function(info) {
                console.log('res', info)
                let s = JSON.parse(info.rawData)
                console.error('s.avatarUrl', s.avatarUrl, s.nickName)
                console.error(s.avatarUrl == '')
                if (s.nickName != null && s.avatarUrl != null) {
                  let avatar = s.avatarUrl
                  avatar = s.avatarUrl == '' ? 'http://zzuisa.cn/unlogin.png' : s.avatarUrl
                  wx.request({
                    url: app.serverUrl + `/user/member/wxlogin`,
                    method: 'post',
                    data: {
                      code: res.code,
                      name: s.nickName,
                      headerImg: avatar,
                      gender: s.gender,
                      province: s.province,
                      city: s.city
                    },
                    success: function(reso) {
                      console.log('resooo', reso)
                      if (reso.data.code == 0) {
                        wx.hideLoading()
                        _this.setData({
                          userInfo: reso.data.content
                        })
                        app.setGlobalUserInfo(reso.data.content)
                        app.globalData.header.Cookie = reso.header["Set-Cookie"];
                        wx.hideLoading()
                        if (_this.data.page != undefined) {
                          let page = _this.data.page
                          wx.navigateTo({
                            url: decodeURIComponent(page.replace('article@', 'article?').replace('video@', 'video?'))
                          })
                        }
                      }

                    }
                  })
                }

              }
            })
          }
        })
      }
    })
  },
  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage(res) {
    let _this = this
    let url = encodeURIComponent(`${_this.data.originUrl}`)
    return {
      title: `【德语助理】我分享了：${_this.data.name}，快来看看吧!`,
      path: `/pages/index/index?page=/pages/video/video@url=${url}&share=share&title=${_this.data.name}`,
      // imageUrl: '/Images/dic.png',
    }
  },
})